package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tanhua.dubbo.server.UserInfoService;
import com.tanhua.model.domain.UserInfo;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Map;

@DubboService
public class UserInfoApiImpl implements UserInfoApi {
    @Autowired
    private UserInfoService userInfoService;

    @Override
    public void save(UserInfo userInfo) {
        userInfoService.save(userInfo);
    }

    @Override
    public void update(UserInfo userInfo) {
        userInfoService.updateById(userInfo);
    }

    @Override
    public UserInfo getById(long id) {
        return userInfoService.getById(id);
    }

    @Override
    public void updateHeadersById(Long userId, String imgUrl) {
        LambdaUpdateWrapper<UserInfo> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(UserInfo::getId, userId);
        updateWrapper.set(UserInfo::getCoverPic, imgUrl);
        userInfoService.update(updateWrapper);
    }

    @Override
    public Map<Long, UserInfo> getByIds(List<Long> ids, UserInfo userInfo) {
            LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        if (userInfo != null) {
            queryWrapper.eq(userInfo.getGender() != null, UserInfo::getGender, userInfo.getGender());
            queryWrapper.le(userInfo.getAge() != null, UserInfo::getAge, userInfo.getAge());
//        queryWrapper.like(userInfo.getCity() != null, UserInfo::getCity, userInfo.getCity());
//        queryWrapper.eq(userInfo.getEducation() != null, UserInfo::getEducation, userInfo.getEducation());
        }
        if (CollUtil.isNotEmpty(ids)) {
            queryWrapper.in(UserInfo::getId, ids);
        }
        List<UserInfo> userInfoList = userInfoService.list(queryWrapper);
//        Map<String, UserInfo> infoMap = CollUtil.fieldValueMap(userInfoList, "id");
        return CollUtil.fieldValueMap(userInfoList, "id");
    }

    @Override
    public IPage findAll(Integer page, Integer pagesize) {
        Page<UserInfo> infoPage = new Page<>(page, pagesize);
        return userInfoService.page(infoPage);
    }

    @Override
    public UserInfo findByNickname(String nickname) {
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(nickname != null, UserInfo::getNickname, nickname);
        return userInfoService.getOne(queryWrapper);
    }
}
